package me.goldze.mvvmhabit.binding.command;

import io.reactivex.functions.Function;

public class ResponseCommand<T, R> {
    private BindingFunction<Boolean> canExecute;
    private BindingFunction<R> execute;
    private Function<T, R> function;

    public ResponseCommand(BindingFunction<R> execute2) {
        this.execute = execute2;
    }

    public ResponseCommand(Function<T, R> execute2) {
        this.function = execute2;
    }

    public ResponseCommand(BindingFunction<R> execute2, BindingFunction<Boolean> canExecute2) {
        this.execute = execute2;
        this.canExecute = canExecute2;
    }

    public ResponseCommand(Function<T, R> execute2, BindingFunction<Boolean> canExecute2) {
        this.function = execute2;
        this.canExecute = canExecute2;
    }

    public R execute() {
        if (this.execute == null || !canExecute()) {
            return null;
        }
        return this.execute.call();
    }

    private boolean canExecute() {
        BindingFunction<Boolean> bindingFunction = this.canExecute;
        if (bindingFunction == null) {
            return true;
        }
        return bindingFunction.call().booleanValue();
    }

    public R execute(T parameter) throws Exception {
        if (this.function == null || !canExecute()) {
            return null;
        }
        return this.function.apply(parameter);
    }
}
